package com.kdtech.analyse.news;
import com.kdtech.analyse.AnalyseNews;
import com.kdtech.utils.HtmlCleaner;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import com.kdtech.crawler.CrawlHTML;
import com.kdtech.crawler.at.UrlArgumentTop;
import com.kdtech.entity.crawler.UrlMeta;
import com.kdtech.entity.data.NewsMeta;
import com.kdtech.utils.DateUtils;
import com.kdtech.utils.StringUtils;
import com.kdtech.utils.HtmlCleaner;

/**
 * 深圳之窗网解析
 * 
 * @author Persh
 * 
 */
public class SzNewsAnalyse implements AnalyseNews {

	private static final String[] regex={ 
		"http://.*.shenchuang.com/.*[0-9]{8}/[0-9]+.shtml", 
		"http://.*.sznews.com/detail.aspx\\?id=[0-9]*"
	};

	
	public boolean isDetailPage(String url) {
		for (int i=0; i < regex.length; i++) {
			if (url.matches(regex[i])) {
				return true;
			}
		}
		return false;
	}

	
	public NewsMeta parserHtml(UrlMeta urlMeta) {
		NewsMeta news=new NewsMeta();

		if (urlMeta.getHtml() == null) {
		}
		String htmltxt=urlMeta.getHtml();

		String url=urlMeta.getUrl();
		news.setUrl(url);
		String title=null;
		String content=null;
		Long date=null;
		String author=null;
		Document doc=Jsoup.parse(htmltxt);
		title=doc.select(".MainL_Article>div.hd>h1").text();
		if(StringUtils.isBlank(title)){
			title=doc.select("strong.font16").text();
		}
		content=HtmlCleaner.getContentHtml(url,doc.select("div#bd_contents"));
		if(StringUtils.isBlank(content)){
			content=HtmlCleaner.getContentHtml(url,doc.select("div.NYcontent1"));
		}
		String text=doc.select("div.tit-bar20").text();
		author=StringUtils.substringBetween(text, "来源：", "|");
		date=DateUtils.matchDate(text);
		if(StringUtils.isBlank(author)){
			Elements elements = doc.select("div.NYcontent span");
			try {
				author = elements.last().text();
				date = DateUtils.matchDate(elements.get(4).text());
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		news.setTitle(StringUtils.trimSpace(title));
		news.setContent(content);
		news.setDate(date);
		news.setAuthor(author);

		return news;
	}

	public static void main(String[] args) {
		SzNewsAnalyse analyse=new SzNewsAnalyse();
		String url="http://wdlh.sznews.com/detail.aspx?id=3675";
		url=UrlArgumentTop.FromatUrl(url);
		// System.err.println(url);
		System.err.println(analyse.isDetailPage(url));
		UrlMeta meta=CrawlHTML.responseToURL(url);
		System.out.println(analyse.parserHtml(meta));
	}

	
	public NewsMeta Update(NewsMeta meta) {
		return null;
	}

	
	public boolean isNeedUpdate() {
		return false;
	}
}
